<template>
  <a-spin :spinning="confirmLoading">
    <div class="info" style="">
      <div>
        <p>设备名称</p>
        <p>{{ this.model.deviceName }}</p>
      </div>
      <div>
        <p>设备ID</p>
        <p>{{ this.model.deviceName }}</p>
      </div>
      <div>
        <p>设备状态</p>
        <p
          :style="{
            color: (this.iotDeviceInfo.state.text || this.model.deviceStatus_dictText) === '在线' ? '#23d523' : '#666'
          }"
        >
          {{ this.iotDeviceInfo.state.text || this.model.deviceStatus_dictText }}
        </p>
      </div>
    </div>
    <a-tabs default-active-key="1" @change="callback">
      <a-tab-pane key="1" tab="基础信息" force-render>
        <j-form-container disabled>
          <a-form-model ref="form" :model="model" slot="detail">
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="设备名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceName">
                  <a-input v-model="model.deviceName" placeholder="请输入设备名称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="设备ID" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceId">
                  <a-input v-model="model.deviceId" placeholder="请输入设备ID"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="产品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceProductId">
                  <j-search-select-tag
                    v-model="model.deviceProductId"
                    dict="ene_device_product,device_product_name,id"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceTypeId">
                  <j-search-select-tag v-model="model.deviceTypeId" dict="ene_device_type,device_type_name,id" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model="model.deviceBrandId_dictText" placeholder="请输入品牌" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="在线状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceStatus">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.deviceStatus"
                    dictCode="device_online_status"
                    placeholder="请选择在线状态"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="采购部门"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="devicePurchaseDeptId"
                >
                  <j-select-depart v-model="model.devicePurchaseDeptId" :multi="true" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="采购人"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="devicePurchaseUserId"
                >
                  <j-select-user-by-dep v-model="model.devicePurchaseUserId" :multi="true" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="采购日期"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="devicePurchaseDate"
                >
                  <j-date
                    placeholder="请选择采购日期"
                    v-model="model.devicePurchaseDate"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="使用部门"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="deviceUseDeptId"
                >
                  <j-select-depart v-model="model.deviceUseDeptId" :multi="true" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item
                  label="使用负责人"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="deviceUseUserId"
                >
                  <j-select-user-by-dep v-model="model.deviceUseUserId" :multi="true" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="设备位置" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="devicePosition">
                  <a-input v-model="model.devicePosition" placeholder="请输入设备位置"></a-input>
                </a-form-model-item>
              </a-col>

              <a-col :span="12">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceRemarks">
                  <a-textarea v-model="model.deviceRemarks" rows="2" placeholder="请输入备注" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="设备图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deviceImages">
                  <img :src="imageUrl" alt="" style="width: 120px; height: 100px" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-tab-pane>
      <a-tab-pane key="2" tab="设备运行情况">
        <a-spin v-if="iotLoad" />
        <div v-if="!iotLoad" style="display: flex;justify-content: space-between;">
          <div style="background-color: rgb(244,246,255);padding:10px 15px;width:245px;margin-bottom: 10px;">
            <p style="color:#666;font-size:16px;margin: 0px;">设备状态</p>
            <p style="color:#000;font-size:18px;margin:5px 0px;">{{ this.iotDeviceInfo.state.text }}</p>
            <p style="color:#666;font-size:14px;margin: 0px;">{{ onlineTime }}</p>
          </div>
          <div style="background-color: rgb(244,246,255);padding:10px 15px;width:245px;margin-bottom: 10px;">
            <p style="color:#666;font-size:16px;margin: 0px;">设备类型</p>
            <p style="color:#000;font-size:18px;margin:5px 0px;">{{ this.iotDeviceInfo.deviceType.text }}</p>
          </div>
          <div style="background-color: rgb(244,246,255);padding:10px 15px;width:245px;margin-bottom: 10px;">
            <p style="color:#666;font-size:16px;margin: 0px;">连接协议</p>
            <p style="color:#000;font-size:18px;margin:5px 0px;">{{ this.iotDeviceInfo.transport }}</p>
            <p style="color:#666;font-size:14px;margin: 0px;">IP地址:&nbsp;&nbsp;{{ this.iotDeviceInfo.address }}</p>
          </div>
          <div style="background-color: rgb(244,246,255);padding:10px 15px;width:245px;margin-bottom: 10px;">
            <p style="color:#333;font-size:16px;margin: 0px;">消息协议</p>
            <p style="color:#000;font-size:18px;margin:5px 0px;">{{ this.iotDeviceInfo.protocol }}</p>
          </div>
        </div>
        <a-table
          v-if="!iotLoad"
          :columns="logColumns"
          :data-source="logData"
          size="middle"
          :pagination="{ defaultPageSize: 5 }"
        >
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="3" tab="生命历程">
        <div style="padding:10px 30px;">
          <a-timeline>
            <a-timeline-item v-for="item in lifes" :key="item.id">
              <div style="background-color: rgb(244,245,247);padding:10px 5px;">
                <span style="display:inline-block;width:100px;text-align: center;color:#000;">{{ item.content }}</span>
                <span style="display:inline-block;width:100px;text-align: center;color:#000;">{{ item.username }}</span>
                <span
                  style="display:inline-block;width:100px;background-color: rgb(210,248,249);text-align: center;color:#000;"
                  >{{ item.dept }}</span
                >
                <span style="display:inline-block;width:200px;text-align: center;color:#000;">{{ item.time }}</span>
                <span style="display:inline-block;color:#000;">{{ item.name }}</span>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </a-tab-pane>
      <a-tab-pane key="4" tab="维修记录">
        <a-table :columns="repairColumns" :data-source="repairData" size="middle" :pagination="{ defaultPageSize: 10 }">
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="5" tab="保养记录">
        <a-table
          :columns="maintainColumns"
          :data-source="maintainData"
          size="middle"
          :pagination="{ defaultPageSize: 10 }"
        >
        </a-table>
      </a-tab-pane>
<!--      <a-tab-pane key="6" tab="巡检记录">-->
<!--        <a-table-->
<!--          :columns="xunjianColumns"-->
<!--          :data-source="xunjianData"-->
<!--          size="middle"-->
<!--          :pagination="{ defaultPageSize: 10 }"-->
<!--        >-->
<!--        </a-table>-->
<!--      </a-tab-pane>-->
<!--      <a-tab-pane key="7" tab="点检记录">-->
<!--        <a-table-->
<!--          :columns="dianjianColumns"-->
<!--          :data-source="dianjianData"-->
<!--          size="middle"-->
<!--          :pagination="{ defaultPageSize: 10 }"-->
<!--        >-->
<!--        </a-table>-->
<!--      </a-tab-pane>-->
      <a-tab-pane key="8" tab="附件">
        <a-table :columns="fileColumns" :data-source="fileData" size="middle" :pagination="{ defaultPageSize: 10 }">
          <span slot="download" slot-scope="text, record">
            <a target="_blank" rel="noopener noreferrer" :href="getFileUrl(record.filePath)">下载</a>
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>
import { httpAction, getAction, iotHttpAction, getFileAccessHttpUrl } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import moment from 'moment'

export default {
  name: 'EneDeviceDetail',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {},
      lifes: [],
      modelFiles: {},
      iotLoad: true,
      iotDeviceInfo: { state: { text: '' }, deviceType: { text: '' }, transport: '', protocol: '' },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {},
      logData: [],
      logColumns: [
        {
          title: '类型',
          dataIndex: 'type.text',
          key: 'type.text',
          width: 150
        },
        {
          title: '时间',
          dataIndex: 'timestamp',
          key: 'timestamp',
          width: 230
        },
        {
          title: '内容',
          dataIndex: 'content',
          key: 'content',
          ellipsis: true
        }
      ],
      fileData: [],
      fileColumns: [
        {
          title: '文件名',
          dataIndex: 'fileName',
          key: 'fileName'
        },
        {
          title: '类型',
          dataIndex: 'typeName',
          key: 'typeName',
          width: 100
        },
        {
          title: '大小KB',
          dataIndex: 'fileSize',
          key: 'fileSize'
        },
        {
          title: '操作',
          dataIndex: 'download',
          scopedSlots: { customRender: 'download' }
        }
      ],
      repairColumns: [
        {
          title: '报修名称',
          align: 'center',
          dataIndex: 'faultRepairName'
        },
        {
          title: '报修单号',
          align: 'center',
          dataIndex: 'faultRepairNo'
        },
        {
          title: '报修人',
          align: 'center',
          dataIndex: 'createBy_dictText'
        },
        {
          title: '报修部门',
          align: 'center',
          dataIndex: 'sysOrgCode_dictText'
        },
        {
          title: '故障类型',
          align: 'center',
          dataIndex: 'faultRepairTypeId_dictText'
        },
        {
          title: '故障时间',
          align: 'center',
          dataIndex: 'faultRepairTime'
        },
        {
          title: '故障报修状态',
          align: 'center',
          dataIndex: 'faultRepairState_dictText'
        },
        {
          title: '分派时间',
          align: 'center',
          dataIndex: 'handleTime'
        },
        {
          title: '完工时间',
          align: 'center',
          dataIndex: 'completeTime'
        }
      ],
      xunjianColumns: [
        {
          title: '设备名称',
          align: 'center',
          dataIndex: 'shebeiname',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '设备编号',
          align: 'center',
          dataIndex: 'shebeibianhao'
        },
        {
          title: '计划名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '计划编号',
          align: 'center',
          dataIndex: 'bianhao'
        },
        {
          title: '巡检周天',
          align: 'center',
          dataIndex: 'xunjianzhouqi'
        },
        {
          title: '巡检项目',
          align: 'center',
          dataIndex: 'xiangmu_dictText'
        },
        {
          title: '计划巡检时间',
          align: 'center',
          dataIndex: 'jihuaxunjianshijian',
          customRender: function(text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          }
        },
        {
          title: '巡检完成时间',
          align: 'center',
          dataIndex: 'xunjianwanchengshijian',
          customRender: function(text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          }
        }
      ],
      dianjianColumns: [
        {
          title: '设备名称',
          align: 'center',
          dataIndex: 'shebeiname'
        },
        {
          title: '设备编号',
          align: 'center',
          dataIndex: 'shebeibianhao'
        },
        {
          title: '计划名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '计划编号',
          align: 'center',
          dataIndex: 'bianhao'
        },
        {
          title: '点检周期（天）',
          align: 'center',
          dataIndex: 'zhouqi'
        },
        {
          title: '点检项目',
          align: 'center',
          dataIndex: 'xiangmu_dictText'
        },
        {
          title: '计划点检时间',
          align: 'center',
          dataIndex: 'jihuadianjianshijian',
          customRender: function(text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          }
        },
        {
          title: '点检负责人',
          align: 'center',
          dataIndex: 'fuzeren_dictText'
        }
      ],
      maintainColumns: [
        // {
        //   title: '工单号',
        //   dataIndex: 'workNo',
        //   key: 'workNo',
        // },
        {
          title: '计划名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '计划编号',
          dataIndex: 'bianhao',
          key: 'bianhao'
        },
        {
          title: '保养层级',
          dataIndex: 'cengji_dictText',
          key: 'cengji_dictText'
        },
        {
          title: '保养方式',
          dataIndex: 'fangshi_dictText',
          key: 'fangshi_dictText'
        },
        {
          title: '保养周期',
          dataIndex: 'jiangeshichang',
          key: 'jiangeshichang'
        },
        {
          title: '状态',
          dataIndex: 'zhuangtai_dictText',
          key: 'zhuangtai_dictText'
        },
        {
          title: '执行人',
          dataIndex: 'fuzeren_dictText',
          key: 'fuzeren_dictText'
        },
        {
          title: '保养日期',
          dataIndex: 'zhixingshijian',
          key: 'zhixingshijian',
          customRender: function(text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          }
        }
      ],
      routeCheckColumns: [
        {
          title: '工单号',
          dataIndex: 'workNo',
          key: 'workNo'
        },
        {
          title: '计划名称',
          dataIndex: '',
          key: ''
        },
        {
          title: '计划编号',
          dataIndex: '',
          key: ''
        },
        {
          title: '巡检周期（天）',
          dataIndex: '',
          key: ''
        },
        {
          title: '巡检项',
          dataIndex: '',
          key: ''
        },
        {
          title: '计划巡检日期',
          dataIndex: '',
          key: ''
        },
        {
          title: '巡检完成日期',
          dataIndex: '',
          key: ''
        },
        {
          title: '执行人',
          dataIndex: '',
          key: ''
        }
      ],
      pointCheckColumns: [
        {
          title: '工单号',
          dataIndex: '',
          key: ''
        },
        {
          title: '计划名称',
          dataIndex: '',
          key: ''
        },
        {
          title: '计划编号',
          dataIndex: '',
          key: ''
        },
        {
          title: '点检周期（天）',
          dataIndex: '',
          key: ''
        },
        {
          title: '点检项',
          dataIndex: '',
          key: ''
        },
        {
          title: '计划点检日期',
          dataIndex: '',
          key: ''
        },
        {
          title: '点检完成日期',
          dataIndex: '',
          key: ''
        },
        {
          title: '执行人',
          dataIndex: '',
          key: ''
        }
      ],
      repairData: [],
      url: {
        add: '/device/eneDevice/add',
        edit: '/device/eneDevice/edit',
        queryById: '/device/eneDevice/queryById',
        typeQueryById: '/device/eneDeviceType/queryById'
      },
      maintainData: [],
      xunjianData: [],
      dianjianData: []
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    onlineTime() {
      switch (this.iotDeviceInfo.state.text) {
        case '在线':
          return '上线时间：' + moment(this.iotDeviceInfo.onlineTime).format('YYYY-MM-DD HH:mm:ss')
        case '离线':
          return '下线时间：' + moment(this.iotDeviceInfo.offlineTime).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    imageUrl() {
      return `http://${window.location.host}/tsl-boot/sys/common/static/${this.model.deviceImages}`;
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    detail(record) {
      this.lifes = []
      this.model = Object.assign({}, record)
      this.modelFiles = { deviceTypeFiles: '' }
      this.visible = false
      this.lifes.push({
        time: record.devicePurchaseDate,
        content: '设备采购',
        dept: record.devicePurchaseDeptId_dictText,
        username: record.devicePurchaseUserId_dictText
      })
      this.lifes.push({
        time: record.createTime,
        content: '设备创建',
        dept: record.sysOrgCode_dictText,
        username: record.createBy_dictText
      })
      this.lifes.push({
        content: '......',
        time: '[以下只展示最近5条] ▼'
      })
      this.getLifeData()
    },
    callback(e) {
      switch (e) {
        case '8':
          this.deviceTypeFiles()
          break
        case '2':
          this.iotLoad = true
          this.iotDeviceMonitor()
          break
        case '5':
          this.getBaoyangData()
          break
        case '4':
          this.getRepairData()
          break
        case '6':
          this.getXunjianData()
          break
        case '7':
          this.getDianjianData()
          break
      }
    },
    getXunjianData() {
      getAction('/gongdan/gdXunjianGongdan/list', { shebei: this.model.id, pageSize: 100 }).then(res => {
        this.xunjianData = res.result.records
      })
    },
    getDianjianData() {
      getAction('/gongdan/gdDianjianGongdan/list', { shebei: this.model.id, pageSize: 100 }).then(res => {
        this.dianjianData = res.result.records
      })
    },
    getBaoyangData() {
      getAction('/gongdan/gdBaoyangGongdan/list', { shebei: this.model.id, pageSize: 100 }).then(res => {
        this.maintainData = res.result.records
      })
    },
    getRepairData() {
      getAction('/repair/eneFaultRepairHandle/list', { faultRepairDeviceId: this.model.deviceId, pageSize: 100 }).then(
        res => {
          this.repairData = res.result.records
        }
      )
    },
    getLifeData() {
      getAction('/device/viewDeviceLifeline/list', { deviceId: this.model.deviceId, pageSize: 5 }).then(res => {
        res.result.records.forEach(record => {
          this.lifes.push({
            time: record.createTime,
            content: record.content,
            dept: record.departName,
            username: record.realname,
            name: record.name
          })
        })
      })
    },
    //
    deviceTypeFiles() {
      getAction(this.url.typeQueryById, { id: this.model.deviceTypeId }).then(res => {
        this.fileData = res.result.files
      })
    },
    iotDeviceMonitor() {
      //
      iotHttpAction(`/device/instance/${this.model.deviceId}/detail`, null, 'GET').then(data => {
        this.iotLoad = false
        this.iotDeviceInfo = data.result
        this.iotDeviceLogs()
      })
    },
    iotDeviceLogs() {
      iotHttpAction(
        `/device-instance/${this.model.deviceId}/logs?` +
          `pageSize=100&pageIndex=0` +
          `&terms[0].column=deviceId&terms[0].value=${this.model.deviceId}` +
          `&sorts[0].name=createTime&sorts[0].order=desc`,
        null,
        'GET'
      ).then(data => {
        // console.log(data);
        let result = data.result.data
        result.forEach(t => (t.timestamp = moment(t.timestamp).format('YYYY-MM-DD HH:mm:ss')))
        this.logData = result
      })
      // this.logData = res.result;
      // console.log(res.result, "iotDeviceLogs");
    },
    getFileUrl(file) {
      return getFileAccessHttpUrl(file)
    }
  }
}
</script>
<style lang="less" scoped>
.info {
  width: 100%;
  background-color: RGBA(245, 245, 245, 1);
  padding: 20px;
  display: flex;

  p {
    margin: 0px;
  }

  div {
    width: 150px;
  }

  div > p:nth-child(1) {
    color: #666;
  }

  div > p:nth-child(2) {
    color: #000;
    font-weight: 400;
  }
}

.ant-form-item {
  margin-bottom: 5px;
}

.ant-modal-body {
  padding: 5px 10px;
}
/deep/ .ant-timeline-item-head-blue {
  top: 6px;
  width: 18px;
  height: 18px;
  background-color: rgb(0, 101, 255);
  left: -4px;
  border-color: rgb(0, 101, 255);
}
/deep/ .ant-timeline-item-tail {
  top: 17px;
}
</style>
